package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.MongoDBConstants;
import cc.linker.steplink.crm.commons.RandomCodeGenerator;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.dao.*;
import cc.linker.steplink.crm.domain.BindCustomerInfoPo;
import cc.linker.steplink.crm.domain.Customer;
import cc.linker.steplink.crm.domain.CustomerInfo;
import cc.linker.steplink.crm.domain.Track;
import cc.linker.steplink.crm.merchant.service.PublicMenuService;
import cc.linker.steplink.crm.merchant.util.DateUtil;
import cc.linker.steplink.crm.merchanth5.dao.OverViewInfoDao;
import cc.linker.steplink.crm.merchanth5.pojo.coupon.CustomerCouponVo;
import cc.linker.steplink.crm.merchanth5.service.CustomerIntegralService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseCode;
import cc.linker.steplink.crm.response.ResponseException;
import cc.linker.steplink.crm.service.CustomerService;
import cc.linker.steplink.crm.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@EnableAsync
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    private CustomerDao customerDao;

    @Autowired
    private CustomerSourceDao customerSourceDao;

    private CustomerInfoDao customerInfoDao;

    private TrackDao trackDao;

    private MongoTemplate mongoTemplate;

    private UserBaseDao userBaseDao;

    private GroupDao groupDao;

    private PreciseDao preciseDao;

    private AwakenDao awakenDao;

    private ActionLogDao actionLogDao;

    private LevelDao levelDao;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OverViewInfoDao overViewInfoDao;
    @Autowired
    private PublicMenuService publicMenuService;

    @Autowired
    private CustomerIntegralService customerIntegralService;

    @Autowired
    private IUserService userService;
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private YzjRequest yzjRequest;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public CustomerServiceImpl(CustomerDao customerDao, CustomerInfoDao customerInfoDao, TrackDao trackDao, MongoTemplate mongoTemplate, UserBaseDao userBaseDao, GroupDao groupDao, PreciseDao preciseDao, AwakenDao awakenDao, ActionLogDao actionLogDao, LevelDao levelDao) {
        this.customerDao = customerDao;
        this.customerInfoDao = customerInfoDao;
        this.trackDao = trackDao;
        this.mongoTemplate = mongoTemplate;
        this.userBaseDao = userBaseDao;
        this.groupDao = groupDao;
        this.preciseDao = preciseDao;
        this.awakenDao = awakenDao;
        this.actionLogDao = actionLogDao;
        this.levelDao = levelDao;
    }

    /**
    * @Description：获取用户分页列表
    * @DateTime：2021/1/19 18:09
    * @Params：
    * @Return：
    */
    @Override
    public List<Map<String,Object>> getCustomerPageList(Map map){
        List<Map<String, Object>> maps = customerDao.getCustomerPageList(map);
        this.addCustomerSuffix(maps);
        return maps;
    }

    @Override
    public List<Map<String, Object>> listCustomer(Map map) {
        List<Map<String, Object>> maps = customerDao.listCustomer(map);
        List<Map<String, Object>> levels = levelDao.listLevels(map);
        for (Map<String, Object> info : maps) {
            map.put("levels", levels);
            // 当前成长积分
            String levelName = "";
            Integer levelOrder = 0;
            String levelId = "";
            if (!StringUtils.isEmpty(info.get("levelId"))) {
                levelId = info.get("levelId").toString();
            }
            if (levels.size() > 0) {
                //获取最后一个等级
                for (int i = 0; i < levels.size(); i++) {
                    Map<String, Object> level = levels.get(i);
                    //获取当前等级数据
                    if (levelId.equals(level.get("levelId").toString())) {
                        levelOrder = (Integer) levels.get(i).get("levelOrder");
                        levelName = levels.get(i).get("levelName").toString();
                        break;
                    }
                }
            }
            info.put("levelName", levelName);
            info.put("levelOrder", levelOrder);
            String customerAreaStr2 = "";
            if (!StringUtils.isEmpty(info.get("customerArea"))) {
                String customerAreaStr = info.get("customerArea").toString().replace("中国", "");
                customerAreaStr2 = customerAreaStr.replace("@", " ");
            }
            info.put("customerAreaStr", customerAreaStr2);
            info.put("createTime", info.get("createTime").toString().replace(".0", ""));
        }
        this.addCustomerSuffix(maps);
        return maps;
    }

    /**
    * @Description：组装用户数据
    * @DateTime：2021/1/19 15:05
    * @Params：
    * @Return：
    */
    @Override
    public List<Map<String, Object>> assembleCustomerExportInfo(List<Map<String, Object>> customerList,String orgId) {
        if (customerList == null || customerList.size() == 0) {
            return customerList;
        }
        Double totalPage = 0.0;
        if(customerList.size()>1000){
            totalPage =Math.ceil(customerList.size() / 1000);
        }else{
            totalPage = 1.0;
        }
        List<String> fields = new ArrayList();
        fields.add(IntegralEnums.customerScore.toString());
        fields.add(IntegralEnums.customerGrowthScore.toString());
        for (Integer pageIndex = 1; pageIndex <= totalPage; pageIndex++) {
            Integer residue = customerList.size() - ((pageIndex - 1) * 1000);
            Integer querySize = residue > 1000 ? 1000 : residue;
            List<String> customerIds = new ArrayList<>();
            for (int i = ((pageIndex - 1) * 1000); i < querySize; i++) {
                customerIds.add(customerList.get(i).get("customerId").toString());
            }

            if (customerIds != null && customerIds.size() > 0) {
                Map<String, Object> params = new HashMap<>();
                params.put("customerIds", customerIds);
                params.put("fields", fields);
                List<Map<String, Object>> dataList = this.customerIntegralService.getCustomersScore(params);

                for (Integer j = ((pageIndex - 1) * 1000); j < querySize; j++) {
                    String customerId = customerList.get(j).get("customerId").toString();
                    List<Map<String, Object>> customerScoreInfos = dataList.stream().filter(x -> x.get("customerId").equals(customerId)).collect(Collectors.toList());
                    if (customerScoreInfos != null && customerScoreInfos.size() > 0) {
                        customerList.get(j).put(IntegralEnums.customerScore.toString(), customerScoreInfos.get(0).get(IntegralEnums.customerScore.toString()));
                        customerList.get(j).put(IntegralEnums.customerGrowthScore.toString(), customerScoreInfos.get(0).get(IntegralEnums.customerGrowthScore.toString()));
                    }
                }
            }
            totalPage--;
        }

        Boolean isError = false;
        for (Map<String, Object> customerMap : customerList) {
            //判断是否是雅智捷用户，如果是需要到雅智捷那边拿去积分数值
//            if(customerMap.containsKey("sourceUserId") && customerMap.get("sourceUserId")!=null && !isError) {
//                try {
//                    String integral = this.yzjRequest.queryMemberPoint(customerMap.get("sourceUserId").toString());
//                    customerMap.put(IntegralEnums.customerScore.toString(), integral);
//                } catch (Exception ex) {
//                    LOGGER.error("导出用户列表获取雅智捷积分数据失败----", ex);
//                    isError = true;
//                }
//            }
            if(!customerMap.containsKey(IntegralEnums.customerScore.toString()) || customerMap.get(IntegralEnums.customerScore.toString()) ==null){
                customerMap.put(IntegralEnums.customerScore.toString(),"0");
            }
            if(!customerMap.containsKey(IntegralEnums.customerGrowthScore.toString()) || customerMap.get(IntegralEnums.customerGrowthScore.toString()) ==null){
                customerMap.put(IntegralEnums.customerGrowthScore.toString(),"0");
            }
        }
        return customerList;
    }

    /**
     * 无用户名以手机尾号xxxx用户展示
     *
     * @param maps
     */
    @Override
    public void addCustomerSuffix(List<Map<String, Object>> maps) {
        for (Map<String, Object> customer : maps) {
            String customerName = (String) customer.get("customerName");
            if (!StringUtils.isEmpty(customerName)) {
                continue;
            }
            String customerPhone = (String) customer.get("customerPhone");
            if (StringUtils.isEmpty(customerPhone)) {
                continue;
            }
            String suffix = customerPhone.substring(customerPhone.length() - 4);
            String name = "手机尾号" + suffix + "用户";
            Integer num = customerDao.getPhoneNumBySuffix(suffix);
            if (num != null) {
                name += num;
            }
            customerDao.addPhoneNumBySuffix(suffix);
            String customerId = (String) customer.get("customerId");
            Customer customer1 = new Customer();
            customer1.setCustomerId(customerId);
            customer1.setCustomerName(name);
            customerDao.updateByPrimaryKeySelective(customer1);
            customer.put("customerName", name);
            stringRedisTemplate.delete("home:customer_info_" + customerId);
        }
    }

    @Override
    public Map<String,Object> getCustomerById(String id) throws  GlobalException {
        if (StringUtils.isEmpty(id)) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        return customerDao.getCustomerById(id);
    }

    @Override
    public Map<String, Object> getCustomer(String id,String orgId) throws GlobalException {
        if (StringUtils.isEmpty(id)) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }

        Map<String, Object> customer = customerDao.getCustomer(id);
        //优惠券
        Map<String,Object> params = new HashMap<>();
        params.put("active","customer-coupon-count");
        CouponCustomerInfo customerInfo = CouponCustomerInfo
                .builder()
                .customerId(customer.get("customerId").toString())
                .customerName(customer.get("customerName").toString())
                .customerPhone(!StringUtils.isEmpty(customer.get("customerPhone")) ?  customer.get("customerPhone").toString() :"")
                .cover("")
                .orgId(orgId)
                .build();
        Map data = (Map) couponRequest.doRequest("customer-coupon-count", params, customerInfo);
        Integer couponCount = 0;
        if(data!=null) {
            couponCount = data.containsKey("count") ? (Integer) data.get("count") : 0;
        }


        customer.put("balance", NumberUtils.fenToYuan(Long.valueOf(customer.get("balance").toString())));

        // 客户总消费
        String pay = customerDao.getTotalPayByCid(id);
        customer.put("pay", pay);
        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(id,orgId);
        Long currentGrowthScore = 0L;
        if(integralCustomerInfo!=null && !StringUtils.isEmpty(integralCustomerInfo.get("customerGrowthScore"))){
            currentGrowthScore = Long.valueOf(integralCustomerInfo.get("customerGrowthScore").toString());
        }
        Long integral = 0L;
        if(integralCustomerInfo!=null && !StringUtils.isEmpty(integralCustomerInfo.get("customerScore"))){
            integral = Long.valueOf(integralCustomerInfo.get("customerScore").toString());
        }
        customer.put("integral",integral);
        customer.put("customerGrowthScore",currentGrowthScore);
        List vipList = userService.getVipListByCustomerId(id);
        customer.put("vipList", vipList);
//        String levelName = levelDao.getLevelNameByCustomerId(id);
        // 当前成长积分
        String levelName ="";
        Integer levelOrder =0;


        Map map = new HashMap();
        map.put("orgId",orgId);
        List<Map<String, Object>> levels = levelDao.listLevels(map);
        map.put("levels", levels);
        long tsub=0L;
        long sub = -1L;
        int currentLevelNum = -1;
        if(levels.size()>0) {
            //获取最后一个等级
            Map<String, Object> endLevel = levels.get(levels.size()-1);
            //如果用户当前等级大于最后一个等级的经验值则当前等级就是最后一个等级
            if(currentGrowthScore>= (Long) endLevel.get("levelScore")) {
                levelOrder = (Integer) endLevel.get("levelOrder");
                levelName = endLevel.get("levelName").toString();
                tsub = (Long) endLevel.get("levelScore");
                sub = -1L;
            }else{
                //如果不是最后一个等级，遍历所有找到对应的当前等级
                for (int i = 0; i <= levels.size()-1; i++) {
                    Map<String, Object> level = levels.get(i);
                    //获取当前等级数据
                    if ((Long) level.get("levelScore") > currentGrowthScore) {
                        if (i != 0) {
                            levelOrder = (Integer) levels.get(i - 1).get("levelOrder");
                            levelName = levels.get(i - 1).get("levelName").toString();
                            tsub = (Long) levels.get(i - 1).get("levelScore");
                        }
                        sub = (Long) level.get("levelScore") - currentGrowthScore;
                        break;
                    }
                }
            }
        }
        customer.put("levelName", levelName);
        customer.put("levelOrder", levelOrder);
        customer.put("sub", sub);
        customer.put("tsub", tsub);
        customer.put("couponNum",couponCount);
        return customer;
    }


    @Override
    public void insertCustomer(Customer customer, CustomerInfo customerInfo) throws GlobalException {
        String customerId = RandomCodeGenerator.getCustomerId(Constants.CUSTOMER_CODE_SOURCE_STEPLINK);
        customer.setCustomerId(customerId);
        customer.setCustomerSourceChannel((byte) 0);
        customer.setCustomerAssignmentState(false);
        if (StringUtils.isEmpty(customer.getCustomerName())) {
            throw new GlobalException(new ResponseException(10010, "姓名不能为空"));
        }
        if (StringUtils.isEmpty(customer.getCreateUser())) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        int i = customerDao.insertCustomer(customer);
        customerInfo.setCustomerId(customer.getCustomerId());
        customerInfo.setCustomerInfoId(UUID.randomUUID().toString());
        int j = customerInfoDao.insertSelective(customerInfo);
        if ((i & j) != 1) {
            throw new GlobalException(ResponseCode.FAIL);
        }
    }

    @Override
    public void updateCustomer(Customer customer, CustomerInfo customerInfo, PcUserInfo user) throws GlobalException {
        if (StringUtils.isEmpty(customer.getCustomerId())) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        if (StringUtils.isEmpty(user.getAdminId())) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        if(customerInfo!=null && !StringUtils.isEmpty(customerInfo.getCustomerArea())){
            String customerArea = customerInfo.getCustomerArea();
            customerArea = customerArea.replaceAll("省","");
            customerArea = customerArea.replaceAll("市","");
            customerInfo.setCustomerArea(customerArea);
        }
        customer.setNickName(customer.getCustomerName());
        customer.setCustomerName(null);
        customerDao.updateByPrimaryKeySelective(customer);
        customerInfoDao.updateByCustomerIdSelective(customerInfo);
        Track track = new Track(UUID.randomUUID().toString(),
                customer.getCustomerId(), "由" + user.getAdminName() + "编辑", user.getAdminId(), null, (byte) 0, "", "edit");
        trackDao.insertSelective(track);
    }

    @Override
    public List<Map<String, String>> getOutLine(Map<String, Object> map) throws GlobalException {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        return trackDao.listTrack(map);
    }

    @Override
    public Map<String, Object> getData(String id) throws GlobalException {
        if (StringUtils.isEmpty(id)) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, String> customer = customerDao.getData(id);
        map.put("customer", customer);
        // mongodb中查idp数据
//        if (id.startsWith(Constants.CUSTOMER_CODE_SOURCE_IDP)) {
        Query query = new Query();
        query.addCriteria(Criteria.where("customerId").is(id));
        Map one = mongoTemplate.findOne(query, Map.class, MongoDBConstants.IDP_INFO_COLLECTION);
        if (one != null) {
            List list = (List) one.get("attributes");
            map.put("idp", list);
        } else {
            map.put("idp", null);
        }
        return map;
    }

    @Override
    public Object getLabel(Map<String, Object> map) throws GlobalException {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        if (StringUtils.isEmpty(map.get("orgId"))) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Integer pn = (Integer) map.get("pn");
        Integer pageSize = (Integer) map.get("pageSize");
        if (pn == null || pn <= 0) {
            pn = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 20;
        }
        PageHelper.startPage(pn, pageSize);
        List<Map<String, String>> label = customerDao.getLabel(map);
        if (label.size() == 1 && label.get(0) == null) {
            label.clear();
        }
        return new PageInfo<>(label);
    }

    @Override
    public void note(String adminId, String customerId, String trackRemark) throws GlobalException {
        if (StringUtils.isEmpty(adminId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        if (StringUtils.isEmpty(customerId)) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        if (StringUtils.isEmpty(trackRemark)) {
            throw new GlobalException(new ResponseException(400, "备注内容不能为空"));
        }
        Track track = new Track(UUID.randomUUID().toString(),
                customerId, trackRemark, adminId, null, (byte) 0, "", "note");
        int i = trackDao.insertSelective(track);
        if (i != 1) {
            throw new GlobalException(ResponseCode.FAIL);
        }
    }

    @Override
    public void change(Map<String, String> map) throws GlobalException {
        String id = map.get("customerId");
        if (StringUtils.isEmpty(id)) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        String adminId = map.get("adminId");
        if (StringUtils.isEmpty(adminId)) {
            throw new GlobalException(new ResponseException(400, "新负责人ID不能为空"));
        }
        String operateId = map.get("operateId");
        if (StringUtils.isEmpty(operateId)) {
            throw new GlobalException(ResponseCode.INFO_OBTAIN_FAIL);
        }
        Customer customer = customerDao.selectByPrimaryKey(id);
        String oldAdminId = customer.getAdminId();
        if (!StringUtils.isEmpty(oldAdminId) && adminId.equals(oldAdminId)) {
            throw new GlobalException(new ResponseException(400, "已是该客户的负责人"));
        } else {
            Customer cus = new Customer();
            cus.setCustomerId(id);
            cus.setAdminId(adminId);
            int i = customerDao.updateByPrimaryKeySelective(cus);
            String trackRemark;
            if (StringUtils.isEmpty(oldAdminId)) {
                String newAdminName = userBaseDao.getNameById(adminId);
                trackRemark = "分配负责人" + newAdminName;
                // 更新分配状态
                customerDao.updateState(id);
            } else {
                String oldAdminName = userBaseDao.getNameById(oldAdminId);
                trackRemark = "更换负责人" + oldAdminName;
            }
            Track track = new Track(UUID.randomUUID().toString(),
                    id, trackRemark, operateId, null, (byte) 0, "", "change");
            int j = trackDao.insertSelective(track);
            if ((i & j) != 1) {
                throw new GlobalException(ResponseCode.FAIL);
            }
        }
    }

    @Override
    public List<Map<String, Object>> listGroup(String orgId) {
        return groupDao.list(orgId);
    }

    @Override
    public void insertGroup(Map<String, Object> map) throws GlobalException {
        String groupId = UUID.randomUUID().toString();
        map.put("groupId", groupId);
        String groupName = (String) map.get("groupName");
        if (StringUtils.isEmpty(groupName)) {
            throw GlobalException.build("分群名不能为空");
        }
        String orgId = (String) map.get("orgId");
        Map<String, String> map1 = new HashMap<>();
        map1.put("groupName", groupName);
        map1.put("orgId", orgId);
        if (judgeGroupNameRepeat(map1) > 0) {
            throw GlobalException.build("分群名已存在");
        }
        Object behaviorList = map.get("behaviorList");
        Object userBaseList = map.get("userBaseList");
        Object otherList = map.get("otherList");
        String s1 = JSON.serialize(behaviorList);
        String s2 = JSON.serialize(userBaseList);
        String s3 = JSON.serialize(otherList);
        map.put("include", s1 + "@" + s2 + "@" + s3);
        groupDao.insertGroup(map);
        // 更新人群数量
        List<String> list = countGroup((String) map.get("include"), orgId);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("groupId", groupId);
        map2.put("size", list.size());
        groupDao.updateGroupNum(map2);
        // 更新到关联表
        if (list.size() > 0) {
            Map<String, Object> map3 = new HashMap<>();
            map3.put("customerId", list);
            map3.put("groupId", groupId);
            groupDao.insertBatch(map3);
        }
    }

    @Override
    public void editGroup(Map<String, Object> map) throws GlobalException {
        if (StringUtils.isEmpty(map.get("groupId"))) {
            throw GlobalException.build("分群ID不能为空");
        }
        if (judgeGroupNameRepeat(map) > 0) {
            throw GlobalException.build("分群名已存在");
        }
        Object behaviorList = map.get("behaviorList");
        Object userBaseList = map.get("userBaseList");
        Object otherList = map.get("otherList");
        if (behaviorList != null || userBaseList != null || otherList!=null) {
            String s1 = JSON.serialize(behaviorList);
            String s2 = JSON.serialize(userBaseList);
            String s3 = JSON.serialize(otherList);
            map.put("include", s1 + "@" + s2 + "@" + s3);
        }
        groupDao.editGroup(map);
        // 更新人群数量
        String orgId = (String) map.get("orgId");
        String groupId = (String) map.get("groupId");
        List<String> list = countGroup((String) map.get("include"), orgId);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("groupId", groupId);
        map2.put("size", list.size());
        groupDao.updateGroupNum(map2);
        // 删除关联表中数据
        groupDao.delGroupRel(groupId);
        // 更新到关联表
        if (list.size() > 0) {
            Map<String, Object> map3 = new HashMap<>();
            map3.put("customerId", list);
            map3.put("groupId", groupId);
            groupDao.insertBatch(map3);
        }

        List<String> groupIds = new ArrayList<>();
        groupIds.add(groupId);
    }

    @Override
    public void delGroup(List<String> groupIds,String orgId) throws GlobalException {
        for (String groupId : groupIds) {
            if (StringUtils.isEmpty(groupId)) {
                throw new GlobalException(ResponseCode.ID_NULL);
            }
            groupDao.delGroup(groupId);
            preciseDao.delGroup(groupId);
            awakenDao.delGroup(groupId);
            groupDao.delGroupRel(groupId);
        }
    }

    @Override
    public List<Map<String, String>> getGroupName(String orgId) {
        return groupDao.getGroupName(orgId);
    }

    @Override
    public Map<String, Object> getGroup(String id) throws GlobalException {
        if (StringUtils.isEmpty(id)) {
            throw new GlobalException(ResponseCode.ID_NULL);
        }
        Map<String, Object> map = groupDao.getGroup(id);
        String include = "";
        if(!StringUtils.isEmpty(map.get("include"))){
            include = map.get("include").toString();
        }
        if (!StringUtils.isEmpty(include) && include.contains("@")) {
            String[] split = include.split("@");
            String s1 = split[0];
            Object behaviorList = JSON.parse(s1);
            String s2 = split[1];
            Object userBaseList = JSON.parse(s2);

            List otherList = new ArrayList();
            if(split.length==3) {
                String s3 = split[2];
                otherList = (List) JSON.parse(s3);
            }
            map.put("behaviorList", behaviorList);
            map.put("userBaseList", userBaseList);
            map.put("otherList", otherList);
        }
        map.remove("include");
        return map;
    }

    /**
     * @param s 分群规则json串
     * @return 用户ID列表
     * @behaviorList key:1-最近有对话
     * key:2-最近无对话
     * key:3-最近有访问
     * key:4-最近无访问
     * key:5-关注公众号时间
     * key:6-标签
     * @userBaseList key:1-性别
     * key:2-地区
     * key:3-角色  1 联盟商家 2 加盟代理 3 推广员
     * key:4-来源  2 微信 5 小程序 6 APP
     * key:5-生日  1992-12-06  1992-%  1992-12-%  %-12-06  %-06 1992-%-06 %-12-%
     */
    @Override
    public List<String> countGroup(String s, String orgId) {
        if (StringUtils.isEmpty(s) || !s.contains("@")) {
            LOGGER.info("分群规则不合法");
            return null;
        }
        if (StringUtils.isEmpty(orgId)) {
            LOGGER.info("机构ID为空");
            return null;
        }
        String[] split = s.split("@");
        String sp1 = split[0];
        List behaviorList = (List) JSON.parse(sp1);
        String sp2 = split[1];
        List userBaseList = (List) JSON.parse(sp2);
        List otherList = new ArrayList();
        if(split.length==3) {
            String sp3 = split[2];
            otherList = (List) JSON.parse(sp3);
        }


        Map<String, Object> map = new HashMap<>();

        for (Object o : behaviorList) {
            if (o instanceof Map) {
                Integer key = (Integer) ((Map) o).get("key");
                //最后互动时间剩余、公众号不活跃时长
                if (25 == key || 24 == key) {
                    List<Integer> timeList = (List) ((Map) o).get("value");
                    int start,end;
                    if(25 == key){
                        start = 48 - timeList.get(0);
                        end = 48 - timeList.get(1);
                        if (end < 0 || end > start) {
                            throw GlobalException.build("参数错误");
                        }
                    }else{
                        if(timeList.get(0) > timeList.get(1)){
                            throw GlobalException.build("参数错误");
                        }
                        end = 48 + timeList.get(0);
                        start = 48 + timeList.get(1);
                    }
                    //最后互动时间剩余、公众号不活跃时长共用 y、z
                    Date curDate = new Date();
                    String startTime = DateUtil.dateStr(DateUtil.miniuteRoler(curDate, -60 * start), "yyyy-MM-dd HH:mm:ss");
                    String endTime = DateUtil.dateStr(DateUtil.miniuteRoler(curDate, -60 * end), "yyyy-MM-dd HH:mm:ss");
                    map.put("activeStartTime", startTime);
                    map.put("activeEndTime", endTime);
                }else{

                    switch (key) {
                        case 1: //最近有对话
                            map.put("haveDialogue",((Map) o).get("value"));
                            break;
                        case 2: //最近无对话
                            map.put("noDialogue",((Map) o).get("value"));
                            break;
                        case 3://最近最近有访问
                            map.put("haveVisit",((Map) o).get("value"));
                            break;
                        case 4://最近无访问
                            map.put("noVisit",((Map) o).get("value"));
                            break;
                        case 5://关注公众号时间
                            map.put("addTime",((Map) o).get("value"));
                            break;
                            default:
                                break;
                    }

                    char c = (char) (key + 96);
                    String s1 = String.valueOf(c);
                    map.put(s1, ((Map) o).get("value"));
                }

            }
        }

        for (Object o : userBaseList) {
            if (o instanceof Map) {
                Integer key = (Integer) ((Map) o).get("key");
                switch (key){
                    case 1:
                        map.put("sex",((Map) o).get("value"));
                        break;
                    case 2:
                        map.put("area",((Map) o).get("value"));
                        break;
                    case 4:
                        map.put("source",((Map) o).get("value"));
                        break;
                    case 5:
                        map.put("birthDay",((Map) o).get("value"));
                        break;
                        default:
                            break;
                }
            }
        }
        //其他的策略
        for (Object o : otherList){
            if (o instanceof Map) {
                Integer key = (Integer) ((Map) o).get("key");
                switch (key){
                    case 1:
                        //是否绑定手机号码
                        map.put("isBindPhone",((Map) o).get("value"));
                        break;
                    case 2:
                        //权益卡
                        map.put("vipIds",((Map) o).get("value"));
                        break;
                    case 3:
                        //会员等级
                        List<String> list = (List<String>)((Map) o).get("value");
                        Set set = new HashSet<>(list);
                        list = new ArrayList<>(set);
                        map.put("levelIds",list);
                        break;
                    case 4:
                        //角色
                        map.put("roleTypes",((Map) o).get("value"));
                        break;
                    case 5:
                        //标签
                        map.put("labelIds",((Map) o).get("value"));
                        break;
                    default:
                        break;
                }
            }
        }
        if (!StringUtils.isEmpty(map.get("area"))) {
            String h = (String) map.get("area");
            if (h.contains(",")) {
                String[] split1 = h.split(",");
                h = split1[split1.length - 1];
            }
            if (h.contains("省") || h.contains("市")) {
                h = h.replaceAll("省", "").replaceAll("市", "");
            }
            map.put("area", h);
        }
        map.put("orgId", orgId);
        return groupDao.countGroup(map);
    }

    @Override
    public int judgeGroupNameRepeat(Map map) {
        return groupDao.judgeGroupNameRepeat(map);
    }

    @Override
    public int getCustomerScore(String customerId) {
        return customerDao.getCustomerScore(customerId);
    }

    @Override
    public boolean setCustomerScore(Map map) {
        return 1 == customerDao.setCustomerScore(map);
    }

    @Override
    public List<Map<String, Object>> getActionLog(Map<String, String> map) {
        return actionLogDao.getActionLog(map);
    }

    @Override
    public List<Map<String, Object>> getActionContent(Map<String, String> map) {
        return actionLogDao.getActionContent(map);
    }

    @Override
    public String getCustomerLevel(String customerId) {
        Customer customer = customerDao.selectByPrimaryKey(customerId);
        String orgId = customer.getOrgId();
        Map<String, Object> info = new HashMap<>();
        info.put("orgId", orgId);
        info.put("score", customer.getCustomerGrowthScore());
        return levelDao.getLastLevelName(info);
    }

    @Override
    public List<Map<String, Object>> getRobotUser(String orgIds, int limitNum) {
        return customerDao.getRobotUser(orgIds, limitNum);
    }

    @Override
    public List<Map<String, Object>> getRobotUserMarket(String orgIds, int limitNum) {
        return customerDao.getRobotUserMarket(orgIds, limitNum);
    }

    @Override
    public String getLabelsByOpenidAndToken(String openid, String token) {
        return customerDao.getLabelsByOpenidAndToken(openid, token);
    }

    @Override
    public Integer getCustomerCountByOrgId(String orgId) {
        return customerDao.getCustomerCountByOrgId(orgId);
    }

    @Override
    public void updateRobotActive(String customerId, String type) {
        customerDao.updateRobotActive(customerId, type);
    }

    @Override
    public Map<String, Object> getListCustomerByCid(String id, String orgId) {
        Map<String, Object> customer = customerDao.getListCustomerByCid(id, orgId);
        String source = customerSourceDao.getSourceByCid(id);
        if (!StringUtils.isEmpty(source)) {
            customer.put("customerSourceChannel", source);
        } else {
            customer.put("customerSourceChannel", customer.get("customerSourceChannel").toString());
        }
        Map map = new HashMap();
        map.put("orgId",orgId);
        List<Map<String, Object>> levels = levelDao.listLevels(map);
            // 当前成长积分
        String levelName ="";
        Integer levelOrder =0;
        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customer.get("customerId").toString(),orgId);
        Long currentGrowthScore = 0L;
        if(integralCustomerInfo!=null && !StringUtils.isEmpty(integralCustomerInfo.get("customerGrowthScore"))){
            currentGrowthScore = Long.valueOf(integralCustomerInfo.get("customerGrowthScore").toString());
        }
        if(levels.size()>0) {
            //获取最后一个等级
            Map<String, Object> endLevel = levels.get(levels.size()-1);
            //如果用户当前等级大于最后一个等级的经验值则当前等级就是最后一个等级
            if(currentGrowthScore> (Long) endLevel.get("levelScore")) {
                levelOrder = (Integer) endLevel.get("levelOrder");
                levelName = endLevel.get("levelName").toString();
            }else{
                //如果不是最后一个等级，遍历所有找到对应的当前等级
                for (int i = 0; i < levels.size(); i++) {
                    Map<String, Object> level = levels.get(i);
                    //获取当前等级数据
                    if ((Long) level.get("levelScore") > currentGrowthScore) {
                        if (i != 0) {
                            levelOrder = (Integer) levels.get(i - 1).get("levelOrder");
                            levelName = levels.get(i - 1).get("levelName").toString();
                        }
                        break;
                    }
                }
            }
        }
        customer.put("levelName", levelName);
        customer.put("levelOrder", levelOrder);
        return customer;
    }

    @Override
    public Map<String, Object> getOrgFunctionOrgId(String orgId) {

        return customerDao.getOrgFunctionOrgId(orgId);
    }

    @Override
    public List<String> listCustomerByGroupId(String groupId) {
        return customerDao.listCustomerByGroupId(groupId);
    }

    @Override
    public Map<String, Object> customerClassify(String orgId) {
        Map<String, Object> result = new HashMap<>();
        result.put("all", customerDao.customerClassify(orgId, ""));
        result.put("wx", customerDao.customerClassify(orgId, "2"));
        result.put("xcx", customerDao.customerClassify(orgId, "5,8"));
        result.put("app", customerDao.customerClassify(orgId, "6"));
        result.put("zfb", customerDao.customerClassify(orgId, "7"));
        return result;
    }

    @Override
    public Object dynamic(Map<String, Object> map) {
        String customerId = (String) map.get("customerId");
        String startTime = (String) map.get("startTime");
        String endTime = (String) map.get("endTime");

        Map<String,Object> query = new HashMap<>();
        query.put("customerId",customerId);

//        Query query = new Query();
//        query.addCriteria(Criteria.where("customerId").is(customerId));
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            startTime += " 00:00:00";
            endTime += " 23:59:59";
//            query.addCriteria(Criteria.where("datetime").gte(startTime).lte(endTime));
        } else if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
//            query.addCriteria(Criteria.where("datetime").gte(startTime));
        } else if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        query.put("startTime",startTime);
        query.put("endTime",endTime);
        Integer count = overViewInfoDao.getCustomerDynamic(query);
//        long count = mongoTemplate.count(query, MongoConstant.GOODS_DATA);
        Integer pageIndex = (Integer) map.get("pageIndex");
        Integer pageSize = (Integer) map.get("pageSize");
        if (pageIndex != null && pageSize != null) {
            pageIndex = (pageIndex - 1) * pageSize;
//            pageIndex -= 1;
//            Pageable pageable = new PageRequest(pageIndex, pageSize);
//            query.with(pageable);
        }
        query.put("pageIndex",pageIndex);
        query.put("pageSize",pageSize);
        List<Map<String, Object>> maps = overViewInfoDao.getGoodsData(query);

//                Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "datetime"));
//        query.with(sort);
//        List<GoodsData> maps = mongoTemplate.find(query, GoodsData.class, MongoConstant.GOODS_DATA);
        Map<String, Object> result = new HashMap<>();
        result.put("list", maps);
        result.put("count", count);
        return result;
    }

    @Override
    public Object openList(String orgCode) {
        return groupDao.openList(orgCode);
    }

    @Override
    public Object userOpenIdList(String groupIds) {
        return groupDao.userOpenIdList(groupIds);
    }

    @Override
    public void refreshGroup(Map<String, Object> map) {
        if (!StringUtils.isEmpty(map.get("groupIds"))) {
            String gourpIds = (String) map.get("groupIds");
            String[] split = gourpIds.split(",");
            List<String> list = Arrays.asList(split);
            map.put("groupIds", list);
        } else {
            map.remove("groupIds");
        }
        String orgId = (String) map.get("orgId");

        List<Map<String, Object>> list = groupDao.getOrgGroup(map);
        if (null != list && list.size() > 0) {
            for (Map<String, Object> da : list) {

                String key = "refreshGroup:refreshGroup_" + da.get("groupId").toString();
                String tag = redisTemplate.opsForValue().get(key);
                if (!StringUtils.isEmpty(tag)) {
                    continue;
                }
                redisTemplate.opsForValue().set(key, "1");
                redisTemplate.expire(key, 60, TimeUnit.SECONDS);

                groupDao.delGroupRelation(da.get("groupId").toString());
                String groupId = da.get("groupId").toString();
                String include = da.get("include").toString();
                if (!StringUtils.isEmpty(groupId) && !StringUtils.isEmpty(include) && !StringUtils.isEmpty(orgId)) {
                    // 根据分群的include和orgId,查询所有符合规则的客户
                    List<String> strings = countGroup(include, orgId);
                    int size = strings != null ? strings.size() : 0;
                    // 更新分群人数信息
                    Map<String, Object> mapGroup = new HashMap<>();
                    mapGroup.put("size", size);
                    mapGroup.put("groupId", groupId);
                    groupDao.updateGroupNum(mapGroup);
                    // 更新客户-分群关联表
                    if (strings != null && strings.size() > 0) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("customerId", strings);
                        map1.put("groupId", groupId);
                        groupDao.insertBatch(map1);
                    }
                }
                redisTemplate.delete(key);
            }
        }
    }

    @Override
    public Boolean isExitLiveAccountCustomer(String liveAccount,String orgId){
        return  customerDao.isExitLiveAccountCustomer(liveAccount,orgId) > 0;
    }

    /*
     * 修改用户的创作奖励
     * customerId：用户ID
     * liveAccount:直播账号
     * */
    @Override
    public Boolean updateLiveAccountByCustomerId(String customerId, String liveAccount) {
        return customerDao.updateLiveAccountByCustomerId(customerId, liveAccount) > 0;
    }


    @Override
    public Boolean isExitMarketingAccountCustomer(String marketingAccount,String orgId) {
        return customerDao.isExitMarketingAccountCustomer(marketingAccount, orgId) > 0;
    }

    /*
     * 修改用户的创作奖励
     * customerId：用户ID
     * marketingAccount：营销号账号
     * liveAccount:直播账号
     * */
    @Override
    public Boolean updateMarketingAccountByCustomerId(String customerId, String marketingAccount) {
        return customerDao.updateMarketingAccountByCustomerId(customerId, marketingAccount) > 0;
    }

    @Override
    public String getCustomerIdByMarketing(String marketingAccount){
        return  customerDao.getCustomerIdByMarketing(marketingAccount);
    }

    @Override
    public int getCustomerIntegral(String customerId) {
        return customerDao.getCustomerIntegral(customerId);
    }

    @Override
    public void runOldData(String customerIds) {
        List<Map<String, Object>> groupList = groupDao.getAllGroupList();
        for (Map<String, Object> groupMap : groupList) {
            List blist = new ArrayList();
            List ulist = new ArrayList();
            List olist = new ArrayList();
            String include = (String) groupMap.get("include");
            if (!StringUtils.isEmpty(include) && include.contains("@")) {
                String[] split = include.split("@");
                //只有2个代表老数据
                if (split.length == 2) {
                    String s1 = split[0];
                    List behaviorList = (List) JSON.parse(s1);
                    String s2 = split[1];
                    List userBaseList = (List) JSON.parse(s2);
                    for (Object o : behaviorList) {
                        if (o instanceof Map) {
                            Integer key = (Integer) ((Map) o).get("key");
                            if (key.equals(6)) {
                                ((Map) o).put("key", 5);
                                olist.add(o);
                            } else {
                                blist.add(o);
                            }
                        }
                    }
                    for (Object o : userBaseList) {
                        if (o instanceof Map) {
                            Integer key = (Integer) ((Map) o).get("key");
                            if (key.equals(3)) {
                                ((Map) o).put("key", 4);
                                olist.add(o);
                            } else {
                                ulist.add(o);
                            }
                        }
                    }
                    String a1 = JSON.serialize(blist);
                    String a2 = JSON.serialize(ulist);
                    String a3 = JSON.serialize(olist);
                    groupMap.put("include", a1 + "@" + a2 + "@" + a3);
                    groupDao.editGroup(groupMap);
                }
            }
        }

        if (!StringUtils.isEmpty(customerIds)) {
            String[] customerSplit = customerIds.split(",");
            for (String customerId : customerSplit) {
                Map<String, Object> customerMap = this.customerDao.getCustomer(customerId);
                if (customerMap != null) {
                    String sourceUserId =  (String)customerMap.get("sourceUserId");
                    this.customerIntegralService.upateCustomerLevel(customerId, customerMap.get("orgId").toString(),sourceUserId,null);
                }
            }
        }
    }

    @Async
    @Override
    public void ansyYzjCustomer(Map<String, Object> params) {
        //如果是雅智捷的，需要判断雅智捷用没有用户，没有需要同步
        Map customer = customerDao.getCustomerByMap(params);
        if(customer!=null && customer.size()>0){
            String sourceUserId = RandomCodeGenerator.generateShortUuid();
            Map member = new HashMap();
            member.put("full_name",customer.get("full_name"));
            member.put("mobile",customer.get("mobile"));
            member.put("member_code",sourceUserId);
            if(yzjRequest.addMember(member)){
                //同步成功
                customer.put("sourceUserId", sourceUserId);
                customerDao.updateCustomerSourceUserId(customer);
                if(!StringUtils.isEmpty(params.get("customerlevelId"))){
                    yzjRequest.alterMemberLevel(sourceUserId,"",params.get("customerlevelId").toString(),params.get("orgId").toString());
                }
            }
        }
    }

    @Override
    public int saveCustomer(Map<String, Object> customerData) {
        String customerId = customerData.get("customerId").toString();
        String orgId = customerData.get("orgId").toString();
        String tempUuid = customerData.get("tempUuid").toString();
        int i = 0;
        int j = 0;
        boolean flag = checkParam(customerData);
        if(flag){
            try {
                i = customerDao.saveCustomerInfo(customerData);
                j = customerDao.saveCustomer(customerData);
            }catch (Exception e){
                LOGGER.error("批量修改数据错误：");
                System.out.println(e);
            }
        }else{
            return 0;
        }
        if(!StringUtils.isEmpty(customerData.get("labelName"))){
            String labelNames = customerData.get("labelName").toString();
            String replace = labelNames.replace("，", ",");
            String[] split = replace.split(",");
            String labelNameStr = "";
            for (String labelName : split) {
                String labelId = customerDao.getLabelId(labelName, orgId, customerId);
                if (!StringUtils.isEmpty(labelId)) {
                    int m = customerDao.addCustomerLabel(labelId, customerId);
                    if (m > 0) {
                        if (StringUtils.isEmpty(labelNameStr)) {
                            labelNameStr = labelName;
                        } else {
                            labelNameStr = labelNameStr + "," + labelName;
                        }
                    }
                }
            }
            stringRedisTemplate.opsForValue().set("customer:customer_label_"+tempUuid+customerId,labelNameStr);
            stringRedisTemplate.expire("customer:customer_label_"+tempUuid+customerId,1, TimeUnit.MINUTES);
        }
        if(i==1 && j==1){
            return 1;
        }
        return 0;
    }

    private boolean checkParam(Map<String, Object> customerData){
        if(!StringUtils.isEmpty(customerData.get("customerCompany")) && customerData.get("customerCompany").toString().length()>30){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("customerFax")) && customerData.get("customerFax").toString().length()>30){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("nickName")) && customerData.get("nickName").toString().length()>30){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("customerAddress")) && customerData.get("customerAddress").toString().length()>80){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("customerWxcode")) && customerData.get("customerWxcode").toString().length()>30){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("customerIdcard")) && customerData.get("customerIdcard").toString().length()!=15 && customerData.get("customerIdcard").toString().length()!=18){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("customerBirth"))){
//            if(!(Pattern.compile("[0-9]*")).matcher(String.valueOf(customerData.get("customerBirth"))).matches()){
//                return false;
//            }
            if(customerData.get("customerBirth").toString().length()!=8 && customerData.get("customerBirth").toString().length()!=10){
                return false;
            }
        }
        if(StringUtils.isEmpty(customerData.get("infoCustomerPhone"))){
            return false;
        }
        if(StringUtils.isEmpty(customerData.get("customerId"))){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("infoCustomerPhone")) && customerData.get("infoCustomerPhone").toString().length()!=11){
            return false;
        }
        if(!StringUtils.isEmpty(customerData.get("customerEmail"))){
            String email = customerData.get("customerEmail").toString();
            boolean matches = email.matches("[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}");
            if(!matches){
                return false;
            }
//            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
//            Pattern regex = Pattern.compile(check);
//            Matcher matcher = regex.matcher(email);
//            boolean isMatched = matcher.matches();
//            if(!isMatched){
//                return false;
//            }
        }
        if(!StringUtils.isEmpty(customerData.get("labelName"))){
            String[] labelNames = customerData.get("labelName").toString().split(",");
            if(labelNames.length>10){
                return false;
            }else{
                for (String lab : labelNames ) {
                    if(lab.length()>30){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void addBatchLog(Map<String, Object> customerData) {
        customerDao.addBatchLog(customerData);
    }

    @Override
    public void addBatch(Map<String, Object> batch) {
        customerDao.addBatch(batch);
    }

    @Override
    public void saveBatch(Map<String, Object> batch) {
        customerDao.saveBatch(batch);
    }

    @Override
    public void saveBatchLog(Map<String, Object> batch) {
        customerDao.saveBatchLog(batch);
    }

    @Override
    public List<Map<String, Object>> getBatchList(Map<String, Object> map) {
        return customerDao.getBatchList(map);
    }

    @Override
    public List<Map<String, Object>> getBatchLogList(Map<String, Object> map) {
        return customerDao.getBatchLogList(map);
    }

    @Override
    public Map<String, Object> getBatchInfo(Integer batchId) {
        return customerDao.getBatchInfo(batchId);
    }

    @Override
    public void giveCoupon(Map<String, Object> params) {
        Map<String,Object> coupon = new HashMap<>();
        coupon.put("couponId",params.get("couponId"));
        coupon.put("num",1);
        List<Map<String, Object>> coupons = new ArrayList<>();
        coupons.add(coupon);
        Map<String,Object> param = new HashMap<>();
        param.put("couponList",coupons);
        CouponCustomerInfo customerInfo = CouponCustomerInfo
                .builder()
                .customerId(params.get("customerId").toString())
                .orgId(params.get("orgId").toString())
                .customerName("")
                .customerPhone("")
                .cover("")
                .sourceUserId("")
                .build();
        Object res = couponRequest.doRequest("give-coupons", param, customerInfo);
        List<String> consumptionIds = (List<String>) res;
        if (consumptionIds != null && consumptionIds.size() == 1) {
            //赠送成功
            params.put("vipEffectiveDays",0);
            params.put("vipEffectiveMonth",0);
            customerDao.saveCouponGiveLog(params);

            String couponName = "";
            List<String> couponIds = new ArrayList<>();
            couponIds.add((String)params.get("couponId"));
            Map<String, Object> queryParam = new HashMap<>();
            queryParam.put("couponIds", couponIds);
            queryParam.put("useScene", -1);
            Object result = couponRequest.doRequest("customer-goods-coupon", queryParam, customerInfo);
            List<JSONObject> resList = (List<JSONObject>) result;
            if(null!=resList && resList.size()>0){
                for(JSONObject jo:resList){
                    CustomerCouponVo customerCouponVo = com.alibaba.fastjson.JSON.toJavaObject(jo, CustomerCouponVo.class);
                    couponName = customerCouponVo.getName();
                }
            }
            params.put("trackId",UUID.randomUUID().toString());
            params.put("trackRemark","赠送"+couponName+"卡券一张");
            params.put("trackState",0);
            params.put("trackUuid","");
            params.put("trackType","give");
            saveTrack(params);
        }else{
            throw GlobalException.build("操作失败");
        }
    }

    @Override
    public void saveGiveLog(Map<String, Object> params) {
        customerDao.saveCouponGiveLog(params);
        String days = "";
        if(Integer.parseInt(params.get("vipEffectiveMonth").toString())>0){
            days = params.get("vipEffectiveMonth").toString()+"个月";
        }else if(Integer.parseInt(params.get("vipEffectiveDays").toString())>0){
            days = params.get("vipEffectiveDays").toString()+"天";
        }
        if(null!=params.get("effectiveType") && Integer.parseInt(params.get("effectiveType").toString()) == 1){
            days = "永久";
        }
        params.put("trackId",UUID.randomUUID().toString());
        params.put("trackRemark","赠送"+params.get("name")+"权益卡"+days);
        params.put("trackState",0);
        params.put("trackUuid","");
        params.put("trackType","give");
        saveTrack(params);
    }

    @Override
    public BindCustomerInfoPo getOrgCustomerInfoByCustomerId(String customerId){
        return  this.customerDao.getOrgCustomerInfoByCustomerId(customerId);
    }

    public void saveTrack(Map<String,Object> param){
        customerDao.saveTrack(param);
    }
}
